package com.wstuo.bugfix;

import java.io.InputStream;

import org.apache.log4j.Logger;

import org.owasp.validator.html.AntiSamy;
import org.owasp.validator.html.CleanResults;
import org.owasp.validator.html.Policy;
import org.owasp.validator.html.PolicyException;
import org.owasp.validator.html.ScanException;

import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.util.StringUtils;

/**
 * XSS清洁工
 * 用于过滤XSS
 * @author William
 * @since 2014-11-21
 */
public class XssClean {

    private static final Logger logger = Logger.getLogger(XssClean.class);
    private static Policy policy = null;
    
    public static Policy getPolicy() throws PolicyException {
    	if (policy == null) {
    		InputStream policyFile = AppConfigUtils.class.getResourceAsStream("/antisamy-config.xml");
            policy = Policy.getInstance(policyFile);
    	}
    	return policy;
    }
    
    public static String xssClean(String value) {
        if (StringUtils.hasLength(value)) {
            AntiSamy antiSamy = new AntiSamy();
            try {
                final CleanResults cr = antiSamy.scan(value, getPolicy());
                //安全的HTML输出
                value = cr.getCleanHTML();
            } catch (ScanException e) {
                logger.error("过滤XSS异常");
                //e.printStackTrace();
            } catch (PolicyException e) {
                logger.error("加载XSS规则文件异常: " + e.getMessage());
                //e.printStackTrace();
            }
        }
        return value;
    }
}
